package com.atguigu.spring5_webflux.handler;

import com.atguigu.spring5_webflux.service.UserService;
import com.atguigu.spring5_webflux.service.impl.UserServiceImpl;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.netty.http.server.HttpServer;


import java.io.IOException;

import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RouterFunctions.toHttpHandler;

/**
 * 创建路由、适配器、然后初始化服务器完成适配
 */
public class Server {
    public static void main(String[] args) throws IOException {
        Server server = new Server();
        server.createReactorServer();
        System.out.println("enter to exit");
        System.in.read();
    }

    /**
     * 1 创建Router路由
     * @return
     */
    public RouterFunction<ServerResponse> routingFunction(){


        UserService userService = new UserServiceImpl();
        // 为了调用handler中的方法，创建handler,
        UserHandler handler = new UserHandler(userService);

        // 设置路由
//        GET("/users/{id}") // 定义请求路径
//                .and(accept(APPLICATION_JSON)), // 接收返回什么数据类型格式
//                handler::getUserById); // 调用handler中的哪个方法
        return RouterFunctions.route(
                GET("/users/{id}").and(accept(APPLICATION_JSON)),handler::getUserById)
                .andRoute(GET("/users").and(accept(APPLICATION_JSON)),handler::getAllUsers);
    }

    //  创建适配器和服务器

    /**
     * 2 创建适配器、创建服务器完成适配
     */
    public void createReactorServer(){
        // 路由和handler适配
        // 创建路由
        RouterFunction<ServerResponse> router = routingFunction();
        // 创建handler
        // httphandler 用于http请求，存储http的相关信息
        HttpHandler httpHandler = toHttpHandler(router);
        // 创建适配器
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);

        // 创建服务器
        HttpServer httpServer = HttpServer.create();
        httpServer.handle(adapter).bindNow(); // bindNow 现在立刻进行构建，完成适配器适配，之后就能通过路径来访问接口

    }





}
